const express = require('express')
const fs = require('fs')
const fileUtils = require(process.cwd() + '/src/utils/file')
const config = require(process.cwd() + '/src/config/config')
const tiles = require(process.cwd() + '/src/utils/tiles')

let router = express.Router()

// 删除单个文件的函数，async函数返回的是Promise对象
const deleteImage = async (imagePath) => {
  const isExists = await fileUtils.exists(imagePath)
  if (!isExists) {
    // 文件不存在,直接跳过,判定删除成功
    return
  }
  // 文件存在,进行文件删除
  await fs.promises.unlink(imagePath)
}

const doAction = async (tileset, images) => {
  // 先删除所有选中的图片
  const len = images.length
  let rmList = []
  for (let i = 0; i < len; i++) {
    let rmObj = deleteImage(config.publicPath + images[i].src)
    rmList.push(rmObj)
  }
  
  await Promise.all(rmList)
  
  // 再修改setting信息
  const settingPath = config.tilesetsPath + tileset + '.json'
  let setting = await fs.promises.readFile(settingPath)
  setting = JSON.parse(setting)
  setting.list = setting.list.filter((item) => {
    return !images.some(image => image.id === item.id)
  })
  // 保存到文件
  const buffer = JSON.stringify(setting)
  await fs.promises.writeFile(settingPath, buffer)
  // 注意拼接成前段需求的src再进行返回
  setting.list = tiles.tileImageSrc(setting.list, tileset)
  return setting
}

router.post('/', function(req, res) {
  const images = req.body.images
  const tileset = req.body.tileset

  doAction(tileset, images).then((data) => {
    res.json(data)
  })
  .catch((err) => {
    console.log(err)
    res.sendStatus(500)
  })
})

module.exports = router
